<template>
  <div>
    <div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商品分类" prop="goodsCategoryId">
          <el-cascader
            :placeholder="defaultCategory"
            :props="category"
            @change="goodsCategoryIdChange"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="商品名称" prop="goodsName">
          <el-input
            v-model.trim="ruleForm.goodsName"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="商品简介" prop="goodsIntro">
          <el-input
            type="textarea"
            placeholder="请输入商品简介(100字)"
            v-model.trim="ruleForm.goodsIntro"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="商品价格" prop="originalPrice">
          <el-input-number
            controls-position="right"
            :min="1"
            :max="100000000000"
            v-model.trim="ruleForm.originalPrice"
          >
          </el-input-number>
        </el-form-item>

        <el-form-item label="商品售卖价" prop="sellingPrice">
          <el-input-number
            v-model.trim="ruleForm.sellingPrice"
            controls-position="right"
            :min="1"
            :max="10000000"
          >
          </el-input-number>
        </el-form-item>

        <el-form-item label="商品库存" prop="stockNum">
          <el-input-number
            v-model.trim="ruleForm.stockNum"
            controls-position="right"
            :min="1"
            :max="100000000"
          >
          </el-input-number>
        </el-form-item>

        <el-form-item label="商品标签" prop="tag">
          <el-input
            v-model.trim="ruleForm.tag"
            placeholder="请输入商品小标签"
          ></el-input>
        </el-form-item>

        <el-form-item label="上架状态" prop="goodsSellStatus">
          <el-radio label="0" checked v-model="ruleForm.goodsSellStatus"
            >上架</el-radio
          >
          <el-radio label="1" v-model="ruleForm.goodsSellStatus">下架</el-radio>
        </el-form-item>

        <el-form-item label="商品主图" prop="goodsCoverImg">
          <el-upload
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
            action="/api/upload/file"
            :headers="headers"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :show-file-list="false"
          >
            <img
              class="avatar-uploader-img"
              :src="ruleForm.goodsCoverImg"
              v-if="ruleForm.goodsCoverImg"
            />
            <i class="el-icon-plus avatar-uploader-icon" v-else></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="详细内容" prop="goodsDetailContent">
          <we-editor
            style="border: 1px solid black; height: 400px"
            :toolbar-option="toolbar"
            :editable-option="editable"
            :html.sync="ruleForm.goodsDetailContent"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit()">{{
            $route.query.id ? "立即修改" : "新增"
          }}</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { WeEditor } from "wangeditor5-for-vue2";
import "@wangeditor/editor/dist/css/style.css";
import { useWangEditor } from "wangeditor5-for-vue2";
import api from "@/api";

export default {
  components: { WeEditor },
  name: "XinZeng",
  data() {
    return {
      editor: null,
      defaultCategory: "请选择",
      category: {
        lazy: true,
        async lazyLoad(node, resolve) {
          const { level = 0, value } = node;
          let { resultCode, data } = await api.GoodsManager.categories(
            1,
            1000,
            level + 1,
            value || 0
          );
          if (+resultCode !== 200) {
            this.$message.error("网络繁忙,请稍后再试");
            return;
          }
          const nodes = data.list.map((item) => ({
            value: item.categoryId,
            label: item.categoryName,
            leaf: level > 1,
          }));
          resolve(nodes);
        },
      },
      ruleForm: {
        goodsCategoryId: "",
        goodsName: "",
        goodsIntro: "",
        originalPrice: "1",
        sellingPrice: "1",
        stockNum: "0",
        tag: "",
        goodsSellStatus: "0",
        goodsCoverImg: "",
        goodsDetailContent: "",
      },
      rules: {
        goodsCategoryId: [
          { required: true, message: "请选择商品分类!", trigger: "blur" },
        ],
        goodsName: [
          { required: true, message: "请填写商品名称!", trigger: "blur" },
        ],
        originalPrice: [
          { required: true, message: "请填写商品价格!", trigger: "blur" },
        ],
        sellingPrice: [
          { required: true, message: "请填写商品售价!", trigger: "blur" },
        ],
        stockNum: [
          { required: true, message: "请填写商品库存!", trigger: "blur" },
          {
            type: "number",
            min: 1,
            max: 100000,
            message: "排序值无效!",
            trigger: "blur",
          },
        ],
        goodsCoverImg: [
          { required: true, message: "请上传商品图片!", trigger: "blur" },
        ],
      },
      headers: { token: localStorage.getItem("tk") },
      ...useWangEditor({
        config: {
          placeholder: "请输入正文",
        },
      }),
    };
  },
  methods: {
    /* 表单数值发生变化时 */
    handleChange() {},
    //文件上传成功
    handleAvatarSuccess(response) {
      let { resultCode, data } = response;
      if (+resultCode === 200) {
        this.ruleForm.goodsCoverImg = data;
        return;
      }
      this.handleAvatarError();
    },
    //文件上传失败
    handleAvatarError() {
      this.$message.error("上传失败,请重试!");
    },
    //选中节点变化时触发
    goodsCategoryIdChange(val) {
      this.ruleForm.goodsCategoryId = val[2] || 0;
    },
    //提交或修改
    async submit() {
      try {
        await this.$refs["ruleForm"].validate();
        let sendFunc = this.$api.GoodsManager.goodsInsert,
          data = { ...this.ruleForm };
        let { resultCode, message } = await sendFunc(data);
        if (+resultCode !== 200) {
          this.$message.error(message);
          return;
        }
        this.$message.success("恭喜您,当前操作成功");
        this.$router.push({
          name: "xinzeng",
          path: "xinzeng",
        });
      } catch (_) {
        _;
      }
    },
    //重置
    resetForm() {
      this.$refs["ruleForm"].resetFields();
    },
    //获取数据
    async query() {
      let id = +this.$route.query.id;
      if (!id) return;
      let { resultCode, data } = await this.$api.GoodsManager.goodsInfoID(id);
      if (+resultCode !== 200) {
        this.$message.error("网络繁忙,请稍后再试!");
        return;
      }
      let {
        goodsCategoryId,
        goodsName,
        goodsIntro,
        originalPrice,
        sellingPrice,
        stockNum,
        tag,
        goodsSellStatus,
        goodsCoverImg,
        goodsDetailContent,
      } = data.goods;
      this.ruleForm = {
        goodsCategoryId: goodsCategoryId,
        goodsName: goodsName,
        goodsIntro: goodsIntro,
        originalPrice: originalPrice,
        sellingPrice: sellingPrice,
        stockNum: stockNum,
        tag: tag,
        goodsSellStatus: "" + goodsSellStatus,
        goodsCoverImg: goodsCoverImg,
        goodsDetailContent: goodsDetailContent,
      };
      this.defaultCategory = `${data.firstCategory.categoryName}/${data.secondCategory.categoryName}/${data.thirdCategory.categoryName}`;
    },
  },
  created() {
    this.query();
  },
};
</script>

<style lang="less" scoped>
.handle-goods {
  box-sizing: border-box;
  height: 100%;

  /deep/.el-upload {
    display: block;
  }

  .el-image {
    display: block;
    width: 60px;
    height: 60px;
    margin: 0 auto;
  }

  .avatar-uploader-icon,
  .avatar-uploader-img {
    display: block;
    box-sizing: border-box;
    width: 120px;
    height: 120px;
    line-height: 120px;
    font-size: 24px;
    color: #8c939d;
    border: 1px dashed #d9d9d9;
    cursor: pointer;
  }
}
</style>